package com.sqfw.project.wp.controller;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.sqfw.common.utils.SecurityUtils;
import com.sqfw.common.utils.StringUtils;
import com.sqfw.project.system.domain.SysUser;

import com.sqfw.project.system.service.ISysUserService;
import com.sqfw.project.wp.domain.WpEvaluateSatis;
import com.sqfw.project.wp.domain.vo.*;
import com.sqfw.project.wp.service.TSMSSendLogService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.sqfw.framework.aspectj.lang.annotation.Log;
import com.sqfw.framework.aspectj.lang.enums.BusinessType;
import com.sqfw.project.wp.domain.WpInfo;
import com.sqfw.project.wp.service.IWpInfoService;
import com.sqfw.framework.web.controller.BaseController;
import com.sqfw.framework.web.domain.AjaxResult;
import com.sqfw.common.utils.poi.ExcelUtil;
import com.sqfw.framework.web.page.TableDataInfo;

/**
 * 工单表Controller
 *
 * @author lx
 * @date 2023-06-07
 */
@Api(tags = "工单列表")
@RestController
@RequestMapping("/wp/wp_info")
public class WpInfoController extends BaseController {
    @Autowired
    private IWpInfoService wpInfoService;

    @Autowired
    private TSMSSendLogService tsmsSendLogService;

    @Autowired
    private ISysUserService sysUserService;


    /**
     * 查询未处理工单表列表
     */
    @PreAuthorize("@ss.hasPermi('wp:wp_info:list')")
    @GetMapping("/list")
    public TableDataInfo list(WpInfo wpInfo) throws ParseException {
        //查询我的工单
        if (wpInfo.getMyWpInfo() != null && wpInfo.getMyWpInfo()) {
            //获取工号
            String code = SecurityUtils.getLoginUser().getUser().getCode();
            wpInfo.setCode(code);
        }
        if (StringUtils.isNotEmpty(wpInfo.getNickName())){
            String nickName = wpInfo.getNickName();
            SysUser sysUser = new SysUser();
            sysUser.setNickName(nickName);
            List<SysUser> sysUsers = sysUserService.selectUserList(sysUser);
            List<String> collect = sysUsers.stream().map(SysUser::getCode).collect(Collectors.toList());
            wpInfo.setCodes(collect);

        }
        if ("坐席再次描述处理".equals(wpInfo.getNextState())){
            startPage();
            List<WpInfo> list = wpInfoService.organizerList(wpInfo);
            return getDataTable(list);
        }else {
            startPage();
            List<WpInfo> list = wpInfoService.selectWpInfoList(wpInfo);
            return getDataTable(list);
        }

    }

    /**
     * 待回访工单未处理列表
     */
    @PreAuthorize("@ss.hasPermi('getVistWpInfoList')")
    @GetMapping("/getVistWpInfoList")
    public TableDataInfo getVistWpInfoList(WpInfo wpInfo) throws ParseException {

        if (StringUtils.isNotEmpty(wpInfo.getNickName())){
            String nickName = wpInfo.getNickName();
            SysUser sysUser = new SysUser();
            sysUser.setNickName(nickName);
            List<SysUser> sysUsers = sysUserService.selectUserList(sysUser);
            List<String> collect = sysUsers.stream().map(SysUser::getCode).collect(Collectors.toList());
            wpInfo.setCodes(collect);

        }
        startPage();
        List<WpInfo> list = wpInfoService.getVistWpInfoList(wpInfo);
        return getDataTable(list);
    }

    /**
     * 查询已处理的工单列表(通过处理流程表查询已处理工单)
     *
     * @param wpInfo
     * @return
     * @throws ParseException
     */
    @PreAuthorize("@ss.hasPermi('processedWpInfoList')")
    @GetMapping("/processedWpInfoList")
    public TableDataInfo processedWpInfoList(WpInfo wpInfo) throws ParseException {
        startPage();
        TableDataInfo tableDataInfo = wpInfoService.selectprocessedWpInfoList(wpInfo);
        return tableDataInfo;
    }

    /**
     * 查询已回访工单列表
     *
     * @param wpInfo
     * @return
     */
    @PreAuthorize("@ss.hasPermi('visitWpInfoList')")
    @GetMapping("/visitWpInfoList")
    public TableDataInfo visitWpInfoList(WpInfo wpInfo) {

        startPage();
        TableDataInfo tableDataInfo = wpInfoService.selectVisitWpInfoList(wpInfo);
        return tableDataInfo;
    }

    /**
     * 导出工单表列表
     */
    @Log(title = "工单表", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('wp:wp_info:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, WpInfo wpInfo) throws ParseException {
        List<WpInfo> list = wpInfoService.exportWpInfoList(wpInfo);
        ExcelUtil<WpInfo> util = new ExcelUtil<WpInfo>(WpInfo.class);
        util.exportExcel(response, list, "工单数据");
    }

    /**
     * 获取工单表详细信息
     */
    @PreAuthorize("@ss.hasPermi('wp:wp_info:getInfo')")
    @GetMapping(value = "/{scid}")
    public AjaxResult getInfo(@PathVariable("scid") String scid) {
        WpInfo wpInfo = wpInfoService.selectWpInfoByScid(scid);
        // 解密工单手机号+工单身份证
//        String data = kmsClientUtils.decryptCfb(wpInfo.getWpid(), "解密工单手机号+工单身份证", SysBssSignTypeEnum.WP_PHONENO_IDCARD_ENCRYPT.getKey());
//        if (!StringUtils.isEmpty(data)) {
//            // 解析
//            if (data.contains("--")) {
//                String[] arr = data.split("--");
//                wpInfo.setPhoneno(arr[0]);
//                wpInfo.setCallnum(arr[1]);
//            }else {
//                wpInfo.setPhoneno(data);
//            }
//        }
        return success(wpInfo);
    }



    @PreAuthorize("@ss.hasPermi('getInfoByWpid')")
    @GetMapping(value = "/getInfoByWpid")
    public AjaxResult getInfoByWpid( String wpid) {
        WpInfo wpInfo = wpInfoService.selectWpInfoByWpidFindDetail(wpid);

        return success(wpInfo);
    }

    /**
     * 新增工单表
     */
    @Log(title = "工单表", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('wp:wp_info:add')")
    @PostMapping
    public AjaxResult add(@RequestBody WpInfo wpInfo) {
        if (!("1".equals(wpInfo.getCallFlag())&&"工单暂存".equals(wpInfo.getNextState()))){

            if (StringUtils.isEmpty(wpInfo.getScidType())) {
                return AjaxResult.error("工单来源不能为空！");
            }
            if (StringUtils.isEmpty(wpInfo.getNextState())) {
                return AjaxResult.error("请选择后续操作！");
            }
        }
        if ("12345退单".equals(wpInfo.getNextState())){
            wpInfo.setMemoryInfo("暂存");
            wpInfo.setBackState("0");
        }
        //获取登录人账户
        try {
            SysUser sysUser = SecurityUtils.getLoginUser().getUser();
            wpInfo.setSender(sysUser.getCode());
            wpInfo.setCode(sysUser.getCode());
        } catch (Exception e) {
            return AjaxResult.error("未登录，请登录后重试");
        }
        int i = wpInfoService.insertWpInfo(wpInfo);
        // 工单手机号和工单身份证号组合一起加密
//        String data = wpInfo.getPhoneno();
//        if (!StringUtils.isEmpty(wpInfo.getCallnum())) {
//            data = data + "--" + wpInfo.getCallnum();
//        }
//        kmsClientUtils.encryptCfb(wpInfo.getWpid(), data, SysBssSignTypeEnum.WP_PHONENO_IDCARD_ENCRYPT.getKey());
        return toAjax(i);
    }

    /**
     * 处理工单表
     */
    @Log(title = "工单表", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('wp:wp_info:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody WpInfo wpInfo) {

        if ("12345退单".equals(wpInfo.getNextState())){
            wpInfo.setMemoryInfo("暂存");
            wpInfo.setBackState("0");
        }
        return wpInfoService.updateWpInfo(wpInfo);
    }

    /**
     * 处理工单表
     */
    @Log(title = "工单表", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('wp:wp_info:update')")
    @PostMapping("/update")
    public AjaxResult updateWpInfo(@RequestBody WpInfo wpInfo) {
        return toAjax(wpInfoService.updateWpInfo1(wpInfo));
    }

    /**
     * 删除工单表
     */
    @PreAuthorize("@ss.hasPermi('wp:wp_info:remove')")
    @Log(title = "工单表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{scids}")
    public AjaxResult remove(@PathVariable String[] scids) {
        return toAjax(wpInfoService.deleteWpInfoByScids(scids));
    }

    /**
     * 获取社区工单编号
     *
     * @param channel 必传
     * @return
     */
    @PreAuthorize("@ss.hasPermi('wp:wp_info:getWpId')")
    @GetMapping("/getWpId")
    public AjaxResult getWpId(String channel) {

        if (StringUtils.isEmpty(channel)) {
            return AjaxResult.error("工单通道为空，请确认后重试！");
        }
        String wpId = wpInfoService.getWpId(channel);

        return AjaxResult.success("操作成功！", wpId);
    }

    /**
     * 处理按钮点击调用接口,判断是否处于他人处理中
     *
     * @return
     */
    @GetMapping("/processHandle")
    public AjaxResult processHandle(String scid, Integer onOff, String type) throws Exception {
        if (StringUtils.isEmpty(scid)) {
            AjaxResult result = AjaxResult.error("scid不能为空");
            result.put(AjaxResult.CODE_TAG, 200);
            return result;
        }
        if ("read".equals(type)) {
            return AjaxResult.success();
        }
        String username = SecurityUtils.getUsername();
        Boolean aBoolean = wpInfoService.processHandle(scid, username, onOff);
        if (aBoolean) {
            return AjaxResult.success("操作成功！");
        } else {
            WpInfo wpInfo = wpInfoService.selectWpInfoByScid(scid);
            String currWorker = wpInfo.getCurrWorker();
            SysUser sysUser = sysUserService.selectUserByUserName(currWorker);
            return AjaxResult.error("该工单" + sysUser.getNickName() + ",工号:" + sysUser.getCode() + "正在处理中，请稍后重试！");
        }

    }

    /**
     * 根据手机号，查询工单
     * @param phoneno
     * @return
     */
    @PreAuthorize("@ss.hasPermi('findWpInfoListByPhone')")
    @GetMapping("/findWpInfoListByPhone")
    public AjaxResult findWpInfoListByPhone(String phoneno) {

        List<WpInfo> wpInfos = wpInfoService.findWpInfoListByPhone(phoneno);
        return AjaxResult.success(wpInfos);
    }

    /**
     * 根据手机号和状态查询关联工单 phoneno,nextState 为工单归档
     *
     * @param
     * @param
     * @return
     */
    @PreAuthorize("@ss.hasPermi('findAssociationWp')")
    @PostMapping("/findAssociationWp")
    public AjaxResult findAssociationWp(@RequestBody WpInfo wpInfo) {

        List<WpInfo> wpInfos = wpInfoService.selectWpInfoListByPhoneAndNextState(wpInfo);
        return AjaxResult.success(wpInfos);
    }

    /**
     * 查询处理完成后的工单列表中的工单详细信息
     *
     * @param wpInfo
     * @return
     */
    @PreAuthorize("@ss.hasPermi('getWpInfoDetailed')")
    @GetMapping("/getWpInfoDetailed")
    public AjaxResult getWpInfoDetailed(WpInfo wpInfo) {

        WpInfo info = wpInfoService.getWpInfoDetailed(wpInfo);
        return AjaxResult.success(info);

    }

    /**
     * 更新是否已阅
     *
     * @param wpInfo
     * @return
     */
    @Log(title = "工单更新是否已阅", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('updateWpinfoRead')")
    @PostMapping("/updateWpinfoRead")
    public AjaxResult updateWpinfoRead(@RequestBody WpInfo wpInfo) {
        return toAjax(wpInfoService.updateWpinfoRead(wpInfo));
    }

    /**
     * 批量处理待回访工单
     *
     * @return
     */
    @Log(title = "批量处理待回访工单", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('batchingWpInfos')")
    @PostMapping("/batchingWpInfos")
    public AjaxResult batchingWpInfos(@RequestBody WpInfoVO wpInfoVO) {

        return wpInfoService.batchingWpInfos(wpInfoVO);
    }

    /**
     * 批量发送短信
     * TODO
     *
     * @param wpInfoVO
     * @return
     */
    @Transactional
    @Log(title = "工单待回访批量发送短信", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('batchingSendSMS')")
    @PostMapping("/batchingSendSMS")
    public AjaxResult batchingSendSMS(@RequestBody WpInfoVO wpInfoVO) {
        List<String> phonenos = new ArrayList<>();
        String scids = wpInfoVO.getScids();
        String[] split = scids.split(",");
        for (String scid : split) {
            WpInfo info = wpInfoService.selectWpInfoByScid(scid);
            if (info != null) {
                info.setVistSmsFlag("1");
                wpInfoService.updateVistSmsState(info);
                phonenos.add(info.getPhoneno());
            }
        }
        String receivePhones = StringUtils.join(phonenos, ",");
        tsmsSendLogService.sendSmsBatch(receivePhones, "回访时发送至用户");
        return AjaxResult.success("操作成功！");
    }

    /**
     * 培训助理查询已处理工单详情信息
     *
     * @param processedWpinfoVO
     * @return
     */
    @PreAuthorize("@ss.hasPermi('getProcessedWpinfo')")
    @GetMapping("/getProcessedWpinfo")
    public AjaxResult getProcessedHandleWpinfo(ProcessedWpinfoVO processedWpinfoVO) {

        return AjaxResult.success(wpInfoService.getProcessedHandleWpinfo(processedWpinfoVO));
    }

    /**
     * 查询需要打印的工单信息
     *
     * @param scid
     * @return
     */
    @PreAuthorize("@ss.hasPermi('getPrintWpInfo')")
    @GetMapping("/getPrintWpInfo")
    public AjaxResult getPrintWpInfo(String scid) {

        PrintWpInfoVO printWpInfoVO = wpInfoService.getPrintWpInfo(scid);
        return AjaxResult.success(printWpInfoVO);

    }



    /**
     * 查询本月和上月的工单数
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('getWpInfoEcharts')")
    @GetMapping("/getWpInfoEcharts")
    public AjaxResult getWpInfoEcharts() {

        WpInfoEchartsVO wpInfoEcharts = wpInfoService.getWpInfoEcharts();

        return AjaxResult.success(wpInfoEcharts);

    }

    /**
     * 坐席派发
     *
     * @param wpInfo
     * @return
     */
    @Log(title = "坐席派发", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('allocationWpInfo')")
    @PostMapping("/allocationWpInfo")
    public AjaxResult allocationWpInfo(@RequestBody WpInfo wpInfo) {


        return AjaxResult.success(wpInfoService.allocationWpInfo(wpInfo));
    }

    /**
     * 坐席已处理撤销工单
     * @param info
     * @return
     */
    @Log(title = "坐席已处理撤销工单", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('editRevokeWpInfo')")
    @PostMapping("/editRevokeWpInfo")
    public AjaxResult editRevokeWpInfo(@RequestBody WpInfo info){


        String scid = info.getScid();
        if (StringUtils.isEmpty(scid)){
            return AjaxResult.error("参数为空！");
        }
        return toAjax(wpInfoService.editRevokeWpInfo(scid));

    }

    @PreAuthorize("@ss.hasPermi('getWpInfoByWpid')")
    @GetMapping("/getWpInfoByWpid")
    public AjaxResult getWpInfoByWpid(String wpid){

        WpInfo wpInfo = wpInfoService.selectWpInfoByWpid(wpid);

        return AjaxResult.success(wpInfo);
    }

    /**
     * 退回工单到坐席记录
     * @param wpInfo
     * @return
     */
    @PreAuthorize("@ss.hasPermi('getWpBackInfoList')")
    @GetMapping("/getWpBackInfoList")
    public TableDataInfo getWpBackInfoList(WpInfo wpInfo) throws ParseException {
        startPage();
        List<WpInfo> list = wpInfoService.selectWpBackInfoList(wpInfo);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('updateWpInfoByManagement')")
    @PostMapping("/updateWpInfoByManagement")
    public AjaxResult updateWpInfoByManagement(@RequestBody @Validated WpInfoManagementVO wpInfoManagementVO){

        if (StringUtils.isNotEmpty(wpInfoManagementVO.getNextState())){
            if ("工单回访".equals(wpInfoManagementVO.getNextState())){
                List<String> strings = Arrays.asList("坐席再次描述处理", "工单归档");
                if (!strings.contains(wpInfoManagementVO.getState())){
                    return AjaxResult.error("当前工单无法退回回访组");
                }
            }
        }
        wpInfoService.updateWpInfoByManagement(wpInfoManagementVO);

        return AjaxResult.success();
    }

    @Log(title = "点击满意度", businessType = BusinessType.INSERT)
    @GetMapping("/addWpEvaluateSatis")
    public AjaxResult addWpEvaluateSatis(@RequestParam("wpid") String wpid) {
        if (StringUtils.isEmpty(wpid)) {
            return AjaxResult.success("wpid没有传递");
        }
        WpEvaluateSatis wpEvaluateSatis = new WpEvaluateSatis();
        wpEvaluateSatis.setWpid(wpid);
        return toAjax(wpInfoService.addWpEvaluateSatis(wpEvaluateSatis));
    }

    /**
     * 工单更新12345满意度
     * @param wpInfo
     * @return
     */
    @Log(title = "工单更新12345满意度", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('updateWpInfoSatis')")
    @PostMapping("/updateWpInfoSatis")
    public AjaxResult updateWpInfoSatis(@RequestBody WpInfo wpInfo) {
        return toAjax(wpInfoService.updateWpInfoSatis(wpInfo));
    }

}
